import datetime
import logging
import random
import re

from base.connection import mongodb_util, redis_util
from base.decoration import wechat_authenticated
from base.request import MpBaseHandler, get_user_no
from common.definition import ret_msg
from conf import config
from conf.config import MP_APP_ID, MP_APP_SECRET, DOMAIN
from helper.mp_helper import Partner, upsert_user, create_device, user_join_device, gen_qrcode_scene
from helper.payment.balance import BalanceHandler
from helper.template_messages import balance_notice, signup_notice
from helper.user import UserHelper
from util.str_util import replace_emoji

from wechatpy import WeChatClient
from wechatpy import parse_message
from wechatpy.replies import ArticlesReply, create_reply

logger = logging.getLogger("wechat.handlers.mp")

# 直接关注回复
REPLY_SUBSCRIBE0 = [
    {
        "title": " ",
        "description": " ",
        "image": f"https://{DOMAIN}/static/img/content/push108.jpg",
        "url": f"https://{DOMAIN}/wx/template/message?title=108"
    },
    {
        "title": "点击领取新人礼，每人仅限领一次",
        "description": "点击进入欢迎页",
        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
        "url": f"https://{DOMAIN}/wx/template/message?title=108"
    }
]

# 非门店扫码回复[带参数二维码]
if DOMAIN == "wx.laez9.com":
    REPLY_SUBSCRIBE1 = [
        {
            "title": " ",
            "description": " ",
            "image": f"https://{DOMAIN}/static/img/content/push108.jpg",
            "url": f"https://{DOMAIN}/wx/template/message?title=108"
        },
        {
            "title": "点击领取新人礼，每人仅限领一次",
            "description": "点击领取新人礼，每人仅限领一次",
            "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
            "url": f"https://{DOMAIN}/wx/template/message?title=108"
        }
    ]

else:
    REPLY_SUBSCRIBE1 = [
        {
            "title": " ",
            "description": " ",
            "image": f"https://{DOMAIN}/static/img/content/push108.jpg",
            "url": f"https://{DOMAIN}/wx/template/message?title=108"
        },
        {
            "title": "点击领取新人礼，每人仅限领一次",
            "description": "点击进入欢迎页",
            "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
            "url": f"https://{DOMAIN}/wx/template/message?title=108"
        }
    ]

# 门店扫码回复[公众号二维码]
REPLY_SUBSCRIBE2 = [
    {
        "title": " ",
        "description": " ",
        "image": f"https://{DOMAIN}/static/img/content/bar_push_20211126.jpg",
        "url": f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/bar/index.html"
    },
    {
        "title": "现在去选酒 >>>",
        "description": "点击进入小酒馆",
        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
        "url": f"https://{DOMAIN}/go?url=https://{DOMAIN}/static/bar/index.html"
    }
]

# 普通用户扫描新发卡商家二维码自动绑定微信的回复
REPLY_SUBSCRIBE3 = [
    {
        "title": " ",
        "description": " ",
        "image": f"https://{DOMAIN}/static/img/content/cooperation-succeed20190918.png",
        "url": f"https://{DOMAIN}/wx/register/53/style999"
    },
    {
        "title": "欢迎加盟！点击完成注册",
        "description": "点击进入发卡商户注册页",
        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
        "url": f"https://{DOMAIN}/wx/register/53/style999"
    }
]

# 已有合伙人扫未激活未绑定发卡商家二维码的回复
REPLY_SUBSCRIBE4 = [
    {
        "title": " ",
        "description": " ",
        "image": f"https://{DOMAIN}/static/img/content/activation-successful2019018.png",
        "url": f"https://{DOMAIN}/admin/partner"
    },
    {
        "title": "激活成功！请邀请新用户扫码",
        "description": "点击进入合伙人人后台",
        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
        "url": f"https://{DOMAIN}/admin/partner"
    }
]

# 已有合伙人扫已激活未绑定发卡商家二维码的回复
REPLY_SUBSCRIBE5 = [
    {
        "title": " ",
        "description": " ",
        "image": f"https://{DOMAIN}/static/img/content/cooperation-already.png",
        "url": f"https://{DOMAIN}/admin/partner"
    },
    {
        "title": "您已经是合伙人，请邀请新合作商户扫码注册",
        "description": "点击进入合伙人人后台",
        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
        "url": f"https://{DOMAIN}/admin/partner"
    }
]

# OTHER_REPLY = ["多谢留言！我们将及时处理并与您联系。", "发送成功！您的信息我们将及时处理并与您联系。", "多谢留言！我们将及时处理并与您联系。"]
OTHER_REPLY = ["", "", ""]  # 接入腾讯云智服，取消自动回复


class Entry(MpBaseHandler):
    def __init__(self, application, request, **kwargs):
        super().__init__(application, request, **kwargs)
        self.message = None
        self.client = None
        self.partner = None

    def data_received(self, chunk):
        pass

    @wechat_authenticated
    def get(self):
        echo_str = self.get_argument("echostr", "☺")
        return self.finish(echo_str)

    @wechat_authenticated
    def post(self, *args, **kwargs):
        if not self.partner:
            self.partner = Partner()
        if not self.client:
            self.client = WeChatClient(appid=MP_APP_ID, secret=MP_APP_SECRET,
                                       access_token=self.partner.access_token)
        try:
            xml = self.request.body.decode("utf-8")
            logger.debug(xml)
            self.message = message = parse_message(xml)
            func_name = "on_"
            if message.type == "event":
                func_name += message.event
            else:
                func_name += message.type
            if hasattr(self, func_name):
                func = getattr(self, func_name, None)
                if hasattr(func, '__call__'):
                    return self.finish(func())

        except Exception as e:
            logger.exception(e)
        return self.finish(ret_msg(-1))

    def _execute_scan(self):
        """
        扫码绑定设备
        :return:
        """
        did = str(self.message.scene_id)
        open_id = self.message.source
        logger.info("扫码事件：open_id=%s, 二维码内容=%s" % (open_id, did))
        user = self.client.user.get(open_id)
        # 更新用户信息（兼容旧的处理方式，用户信息存放到mongodb中）
        upsert_user(user)
        if re.match(r'^\d+$', did):
            # 扫设备二维码
            # 尝试创建设备
            logger.info(f"扫码: 扫设备二维码 {did}: 尝试创建设备，用户加入设备 open_id={open_id}")
            create_device(did=did, openid=open_id)
            # 尝试加入设备
            user_join_device(did=did, openid=open_id)
        else:
            # 扫用户/合伙人二维码，绑定合伙人
            return self._bind_partner()

    def _create_new_user(self, agency_uid, recommend_user=None):
        """
        用户不存在时创建用户
        self.client.user.get(open_id) 示例：
        user
        {
            "_id" : ObjectId("591ab5c6cfe803c061f9b378"),
            "_updated" : ISODate("2017-11-29T07:13:37.009Z"),
            "city" : "聊城",
            "country" : "中国",
            "groupid" : 0,
            "headimgurl" : "http://wx.qlogo.cn/mmopen/uXSOzoC3mkVHFITTC34cqlvsCVlp2IXssxhzA
            7eocW29bJpZcdPvYJrd1GoYkAYvWonAdibP82GNSmVDdLaFxic5Q6qenqSibHa/0",
            "language" : "zh_CN",
            "nickname" : "dwsoft",
            "openid" : "o7qyl0kFoPaXIC4R8NXTZpobZ5o0",
            "province" : "山东",
            "remark" : "",
            "sex" : 1,
            "subscribe" : 1,
            "subscribe_time" : 1511855491,
            "tagid_list" : []
        }
        :param agency_uid:
        :param recommend_user:
        :return:
        """
        open_id = self.message.source
        user_dict = self.client.user.get(open_id)
        logger.debug(user_dict)

        class User(object):
            pass

        session = self.get_db_session([
            {"db_table": "ebt_user", "model": User},
        ])
        user = session.query(User).filter_by(ebf_user_id=open_id, ebf_user_type=0).first()
        if not user:
            logger.info("create_new_user open_id=%s" % open_id)
            UserHelper.create_user(self.client.user.get(open_id), agency_uid, recommend_user)
        else:
            logger.info("the user has already existed. open_id=%s" % open_id)
            nickname = user.ebf_user_nickname
            if nickname == "未关注" or nickname is None or nickname == "":
                UserHelper.update_user(self.client.user.get(open_id))

        # self.update_user_level(open_id)  # 取消自动发酒卡
        # 发送用户编号
        # self._number_notice()
        session.close()

    def update_user_level(self, open_id):
        """
        关注公众号的新用户送酒卡
        :return:
        """
        class User(object):
            pass

        session = self.get_db_session([
            {"db_table": "ebt_user", "model": User},
        ])
        user = session.query(User).filter_by(ebf_user_id=open_id).first()
        if not user.ebf_user_level:
            user.ebf_user_level = 1
            session.commit()
        session.close()

    def _number_notice(self):
        """
        餐厅扫码用户发送编号通知
        :return:
        """
        class User(object):
            pass

        session = self.get_db_session([
            {"db_table": "ebt_user", "model": User},
        ])
        open_id = self.message.source
        user_dict = self.client.user.get(open_id)
        try:
            u = session.query(User).filter_by(ebf_user_id=open_id).first()
            if u:
                create_date = u.ebf_user_create_date
                now = datetime.datetime.utcnow()
                minus_time = (now - create_date).total_seconds()
                logger.info("create_date=%s, now=%s, oid: %s" % (create_date, now, open_id))
                nickname = replace_emoji(user_dict.get("nickname", "未关注"))
                if minus_time > float(10):
                    logger.info("Old users do not send code_message:oid=%s, minus_time=%s" % (open_id, minus_time))
                    # no = "无(非第一次关注公众号没有编号)"
                    # tasks.send_number_remind_notice.delay(open_id, no, nickname)
                    return
                redis = redis_util.client
                flag = redis.get("scan_no_%s" % open_id)
                if flag:
                    return
                redis.setex("scan_no_%s" % open_id, 600, 1)
                no = str(get_user_no(open_id))
                end_num = no[-1:]
                u.ebf_user_remarks = no
                session.commit()
                logger.info("start send to code_message: oid=%s, no=%s" % (open_id, no))
                # tasks.send_number_remind_notice.delay(open_id, no, nickname)
                # tasks.create_user_coupon.delay(open_id, no)
                recommend_user = u.ebf_user_recommend_user
                if end_num == "9":
                    now_date = datetime.datetime.now()
                    data = dict(
                        create_date=now_date,
                        open_id=open_id,
                        recommend_user=recommend_user,
                        number=no,
                        nickname=nickname,
                        end_num=end_num,
                        uid=u.ebf_user_agency_uid
                    )
                    try:
                        db = mongodb_util.db
                        db.scan_user_number_info.insert(data)
                    except Exception as e:
                        logger.error(e)
            else:
                logger.info("user does not exist：oid=%s" % open_id)
        except Exception as e:
            logger.error("send code_message fail: open_id=%s, error=%s" % (open_id, str(e)))

    def recharge_balance(self, recommend_user, open_id, nickname):
        """
        奖励推荐人一元余额
        :param recommend_user:
        :param open_id:
        :param nickname:
        :return:
        """
        try:
            money = 0.2
            msg = f"感恩有您，您的朋友{nickname}已关注莱支好酒公众号，赠您{money}元余额用于消费。"
            remark = "多分享多受益！"
            is_success = BalanceHandler.add_manual_money(recommend_user, money, operator="",
                                                         ip="", pay_content="新用户活动充值0.2元")
            if is_success:
                logger.info(f"充值成功：OK 充值{money}元余额 recommend_user={recommend_user}, open_id={open_id}")
                balance_notice(recommend_user, money, msg, remark)
            else:
                logger.error(f"充值失败： NG 充值{money}元余额失败 recommend_user={recommend_user}, open_id={open_id}")
        except Exception as e:
            logger.error("充值失败： NG 充值{money}元余额失败 recommend_user={recommend_user}, open_id={open_id}")

    def _bind_partner(self):
        """
        绑定合伙人和推荐人
        支持合伙人的永久二维码 和 用户的临时二维码（永久二维码是uid，而普通用户是openid）
        oid_o7qyl0kFoPaXIC4R8NXTZpobZ5o0
        uid_3db7d3ec-4157-11e7-b900-00a0d1ed4d50
        :return:
        """
        scene_id = str(self.message.scene_id)
        open_id = self.message.source
        wechat_user = self.client.user.get(open_id)
        nickname = replace_emoji(wechat_user.get("nickname", ""))
        logger.debug(wechat_user)

        if not (scene_id.startswith("uid_") or scene_id.startswith("oid_") or scene_id.startswith("ip")):
            logger.error(f"扫码: 不支持的二维码类型：{open_id=}, {scene_id=}")
            return

        class User(object):
            pass

        class Agency(object):
            pass

        class UserAgency(object):
            pass

        session = self.get_db_session([
            {"db_table": "ebt_user", "model": User},
            {"db_table": "ebt_agency", "model": Agency},
            {"db_table": "ebt_user_agency", "model": UserAgency},
        ])
        agency_uid = None
        recommend_user = None

        # 当前用户
        if scene_id.startswith("uid_"):
            # 处理合伙人的二维码，推荐人就是绑定这个合伙人账户的openid
            agency_uid = scene_id[4:]

            # 特别处理礼品卡印错二维码的问题 - 20190802
            if agency_uid == "ef0add0e-6b98-11e7-a30e-00a0d1edbe70":
                agency_uid = config.DEFAULT_AGENCY_UID

            agency = session.query(Agency).filter_by(ebf_agency_uid=agency_uid).one()
            user_agency = session.query(UserAgency).filter_by(ebf_agency_id=agency.ebf_agency_id).first()
            recommend_user = user_agency.ebf_ua_bind_user_id if user_agency else None
            logger.info(f"扫码: {open_id=}, 合伙人码 {agency_uid=}, 推荐人 {recommend_user=}")

        elif scene_id.startswith("oid_"):
            # 处理普通用户的临时二维码，推荐人就是二维码中的openid，合伙人是拥有二维码的用户所属的合伙人
            recommend_user = scene_id[4:]
            _user = session.query(User).filter_by(ebf_user_id=recommend_user, ebf_user_type=0).one()
            agency_uid = _user.ebf_user_agency_uid
            logger.info(f"扫码: 普通用户码: {open_id=}, 推荐人 {recommend_user=}, 合伙人 {agency_uid=}")

        elif scene_id.startswith("ip"):
            # 处理邀请合伙人 ip=invite_partner
            recommend_user = scene_id[7:]
            _user = session.query(User).filter_by(ebf_user_id=recommend_user, ebf_user_type=0).one()
            agency_uid = _user.ebf_user_agency_uid
            invitor_nickname = _user.ebf_user_nickname
            logger.info(f"扫码: 邀请合伙人码: {open_id=}, {agency_uid=}, 推荐人 {recommend_user=}")

            #  处理被邀请合伙人的微信返回消息
            if scene_id.startswith("ip1oid_"):
                reply_subscribe = [
                    {
                        "title": " ",
                        "description": " ",
                        "image": f"https://{DOMAIN}/static/img/content/partner499.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/1/{recommend_user}"
                    },
                    {
                        "title": f"您的朋友{invitor_nickname}邀请您成为海外酒庄合伙人>>>",
                        "description": f"您的朋友{invitor_nickname}邀请您成为海外酒庄合伙人>>>",
                        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/1/{recommend_user}"
                    }
                ]
            elif scene_id.startswith("ip2oid_"):
                reply_subscribe = [
                    {
                        "title": " ",
                        "description": " ",
                        "image": f"https://{DOMAIN}/static/img/content/winery20190705.jpg",
                        "url": f"https://{DOMAIN}/user/invite/partner/2/{recommend_user}"
                    },
                    {
                        "title": f"您的朋友{invitor_nickname}邀请您加盟莱支好酒经销商",
                        "description": f"您的朋友{invitor_nickname}邀请您加盟莱支好酒经销商",
                        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/2/{recommend_user}"
                    }
                ]
            elif scene_id.startswith("ip0oid_"):
                reply_subscribe = [
                    {
                        "title": " ",
                        "description": " ",
                        "image": f"https://{DOMAIN}/static/img/content/subscribe20181126.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/0/{recommend_user}"
                    },
                    {
                        "title": f"您的朋友{invitor_nickname}邀请您成为酒庄代表",
                        "description": f"您的朋友{invitor_nickname}邀请您成为酒庄代表",
                        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/0/{recommend_user}"
                    }
                ]
            elif scene_id.startswith("ip3oid_"):
                reply_subscribe = [
                    {
                        "title": " ",
                        "description": " ",
                        "image": f"https://{DOMAIN}/static/img/content/199invitation20181230.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/3/{recommend_user}"
                    },
                    {
                        "title": f"您的朋友{invitor_nickname}邀请您注册商家",
                        "description": f"您的朋友{invitor_nickname}邀请您注册商家",
                        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/3/{recommend_user}"
                    }
                ]
            elif scene_id.startswith("ip4oid_"):
                reply_subscribe = [
                    {
                        "title": " ",
                        "description": " ",
                        "image": f"https://{DOMAIN}/static/img/content/199invitation20181230.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/4/{recommend_user}"
                    },
                    {
                        "title": f"您的朋友{invitor_nickname}邀请您成为店员",
                        "description": f"您的朋友{invitor_nickname}邀请您成为店员",
                        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/4/{recommend_user}"
                    }
                ]
            elif scene_id.startswith("ip5oid_"):
                reply_subscribe = [
                    {
                        "title": " ",
                        "description": " ",
                        "image": f"https://{DOMAIN}/static/img/content/199invitation20181230.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/5/{recommend_user}"
                    },
                    {
                        "title": f"您的朋友{invitor_nickname}邀请您成为门店推荐人",
                        "description": f"您的朋友{invitor_nickname}邀请您成为门店推荐人",
                        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/5/{recommend_user}"
                    }
                ]
            elif scene_id.startswith("ip6oid_"):
                reply_subscribe = [
                    {
                        "title": " ",
                        "description": " ",
                        "image": f"https://{DOMAIN}/static/img/content/winery.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/6/{recommend_user}"
                    },
                    {
                        "title": f"您的朋友{invitor_nickname}邀请您成为私人酒庄合伙人",
                        "description": f"您的朋友{invitor_nickname}邀请您成为私人酒庄合伙人",
                        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
                        "url": f"https://{DOMAIN}/user/invite/partner/6/{recommend_user}"
                    }
                ]
            elif scene_id.startswith("ip7oid_"):
                # 注册新门店/行家 20200610
                reply_subscribe = [
                    {
                        "title": " ",
                        "description": " ",
                        "image": f"https://{DOMAIN}/static/img/content/invite_store_wxreply-20210204.jpg",
                        "url": f"https://{DOMAIN}/go?url=/static/register/index.html#/storekeeper?oid={recommend_user}"
                    },
                    {
                        "title": f"您的朋友{invitor_nickname}邀请您注册商家",
                        "description": f"您的朋友{invitor_nickname}邀请您注册商家",
                        "image": f"https://{DOMAIN}/static/img/content/logo-60x60.png",
                        "url": f"https://{DOMAIN}/go?url=/static/register/index.html#/storekeeper?oid={recommend_user}"
                    }
                ]
            else:
                raise Exception(f"扫码: Invalid Parameter: {scene_id=}")

            # 设置微信回复内容
            reply = ArticlesReply(message=self.message, articles=reply_subscribe)

        # 创建/更新/绑定用户
        user = session.query(User).filter_by(ebf_user_id=open_id, ebf_user_type=0).first()
        if not user:
            # 新用户
            logger.info(f"扫码: create_new_user: {open_id=}")
            user = UserHelper.create_user(wechat_user, agency_uid, recommend_user)
            level = user.ebf_user_level
            # level = UserHelper.update_level(open_id, recommend_user)  # 取消自动发会员卡 20210710
            logger.info(f"扫码: 创建用户并绑定合伙人: {open_id=}, {recommend_user=}, {agency_uid=}")

            # 发送用户编号
            # self._number_notice()

            # 给新用户推荐人充值1元余额
            if recommend_user:
                # self.recharge_balance(recommend_user, open_id, nickname)
                # 通知推荐人 - 
                # signup_notice(recommend_user, nickname, open_id)
                pass
        else:
            # 老用户
            nick_name = user.ebf_user_nickname
            if nick_name == "未关注" or nick_name == "" or nick_name is None:
                UserHelper.update_user(wechat_user)

            # 记录用户推荐人（推荐人每次扫码都会更新）
            old_recommend_user = user.ebf_user_recommend_user
            # 禁止自己推荐自己
            if recommend_user and recommend_user != open_id and user.ebf_user_recommend_user != recommend_user:
                user.ebf_user_recommend_user = recommend_user
                session.commit()
                logger.info(
                    f"扫码：更新推荐人，{open_id=}, {recommend_user=}, {old_recommend_user=}, {agency_uid=}")

            # 设定酒卡身份
            level = user.ebf_user_level
            # 取消自动发会员卡
            # if not level:
            #     if scene_id.startswith("uid_") and agency_uid != config.DEFAULT_AGENCY_UID:
            #         user.ebf_user_level = 1
            #         session.commit()
            #         logger.info(f"扫码: 更新用户级别 open_id={open_id}")
            #     elif scene_id.startswith("oid_") and _user.ebf_user_level:
            #         user.ebf_user_level = 1
            #         session.commit()
            #         logger.info(f"扫码: 更新用户级别 open_id={open_id}")

            # 如果已经所属合伙人不是公司默认合伙人，不重复绑定
            if user.ebf_user_agency_uid and user.ebf_user_agency_uid != config.DEFAULT_AGENCY_UID:
                logger.debug(f"扫码：已绑定过合伙人: {open_id=}, agency_uid={user.ebf_user_agency_uid}")
            else:
                # 重新绑定合伙人
                user.ebf_user_agency_uid = agency_uid
                logger.info(f"扫码：重新绑定合伙人，{open_id=}, {recommend_user=}, {agency_uid=}")
                session.commit()
                # 通知合伙人 20220414 取消通知
                # signup_notice(recommend_user, nickname, open_id)

        if scene_id.startswith("oid_"):
            if level:
                # 设置微信回复内容
                reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE1)
            else:
                reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE1)

        if scene_id.startswith("uid_"):
            # 设置扫合伙人码微信回复内容
            # 如果扫描未绑定微信的发卡人二维码， 自动绑定微信

            if user_agency and user_agency.ebf_ua_bind_user_id:
                # 合伙人二维码已经绑定合伙人微信，正常回复
                if agency_uid == config.DEFAULT_AGENCY_UID:
                    # 扫门店码（默认合伙人）回复
                    reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE2)
                    logger.info(f"扫码: 回复扫门店码（公司默认） {open_id=} {agency_uid=}")
                else:
                    # 扫合伙人码回复
                    reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE1)
                    logger.info(f"扫码: 回复扫合伙人码 {open_id=} {agency_uid=}")
            else:
                # 判断扫码用户是否已经是合伙人
                ua = session.query(UserAgency).filter_by(ebf_ua_bind_user_id=open_id).first()
                if ua:
                    if agency.ebf_agency_parent_id == 0:
                        agency.ebf_agency_parent_id = ua.ebf_agency_id
                        session.commit()
                        reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE4)
                        logger.info(f"扫码: 用户是合伙人，激活新发卡人账户 {open_id=} {agency_uid=}")
                    else:
                        reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE5)
                        logger.info(f"扫码: 用户是合伙人扫已激活新发卡人账户: {open_id=}, {agency_uid=}")
                else:
                    # # 普通用户扫新发卡商家二维码，自动绑定，邀请注册
                    # if not user_agency:
                    #     agency_id = agency.ebf_agency_id
                    #     _user_agency = UserAgency()
                    #     _user_agency.ebf_user_id = f"P{agency_id}"
                    #     _user_agency.ebf_agency_id = agency_id
                    #     _user_agency.ebf_ua_bind_user_id = open_id
                    #     session.add(_user_agency)
                    #     session.commit()
                    #     reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE3)
                    #     logger.info(f"扫码: 绑定发卡人微信 open_id={open_id} agency_uid={agency_uid}")
                    # elif not user_agency.ebf_ua_bind_user_id:
                    #     user_agency.ebf_ua_bind_user_id = open_id
                    #     session.commit()
                    #     reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE3)
                    #     logger.info(f"扫码: 绑定发卡人微信 open_id={open_id} agency_uid={agency_uid}")
                    # # 用户微信账号绑定到自己合伙人名下
                    # UserHelper.update_agency_uid(open_id, agency_uid)

                    # 改为发卡人账号不注册，扫合伙人码直接回复 - 20191010
                    if agency.ebf_agency_sub_type == 3:
                        # 扫发卡人二维码，回复店内点酒
                        reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE1)
                        logger.info(f"扫码: 回复扫合伙人码: {open_id=}, {agency_uid=}")
                    else:
                        # 扫非发卡人二维码，正常回复
                        reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE1)
                        logger.info(f"扫码: 回复扫合伙人码 {open_id=}, {agency_uid=}")
        session.close()
        return reply.render()

    def on_subscribe(self):
        """
        关注事件
        :return:
        """
        logger.info(f"[!扫码]直接关注: 绑定默认合伙人 open_id={self.message.source}")
        # 尝试创建用户，直接关注公众号的用户属于默认合伙人，并且没有推荐人
        self._create_new_user(agency_uid=config.DEFAULT_AGENCY_UID, recommend_user=None)
        reply = ArticlesReply(message=self.message, articles=REPLY_SUBSCRIBE1)
        # 转换成 XML
        return reply.render()

    def on_subscribe_scan(self):
        """
        未关注用户扫描带参数二维码事件
        :return:
        """
        scene_id = str(self.message.scene_id)
        logger.info(f"扫码: 未关注用户扫码: {scene_id}")

        if not re.match(r'^\d+$', scene_id):
            # 发送用户编号
            # self._number_notice()
            pass
        return self._execute_scan()

    def on_scan(self):
        """
        已关注用户扫描带参数二维码事件
        :return:
        """
        scene_id = str(self.message.scene_id)
        logger.info(f"扫码: 已关注用户扫码: {scene_id}")
        return self._execute_scan()

    def on_text(self):
        """
        文本消息
        :return:
        """
        message = self.message
        # replies = ["你真棒!", "真的嘛?", "然后呢~"]
        replies = OTHER_REPLY
        reply = create_reply(replies[random.randint(0, 2)], message=message)
        # 转换成 XML
        xml = reply.render()
        return xml

    def on_image(self):
        message = self.message
        replies = OTHER_REPLY
        reply = create_reply(replies[random.randint(0, 2)], message=message)
        # 转换成 XML
        xml = reply.render()
        return xml

    def on_voice(self):
        message = self.message
        replies = OTHER_REPLY
        reply = create_reply(replies[random.randint(0, 2)], message=message)
        # 转换成 XML
        xml = reply.render()
        return xml

    def on_video(self):
        message = self.message
        replies = OTHER_REPLY
        reply = create_reply(replies[random.randint(0, 2)], message=message)
        # 转换成 XML
        xml = reply.render()
        return xml

    def on_shortvideo(self):
        message = self.message
        replies = OTHER_REPLY
        reply = create_reply(replies[random.randint(0, 2)], message=message)
        # 转换成 XML
        xml = reply.render()
        return xml

    def on_location(self):
        message = self.message
        reply = create_reply("", message=message)
        # 转换成 XML
        xml = reply.render()
        return xml

    def on_link(self):
        message = self.message
        replies = OTHER_REPLY
        reply = create_reply(replies[random.randint(0, 2)], message=message)
        # 转换成 XML
        xml = reply.render()
        return xml


class QRScene(MpBaseHandler):
    def get(self):
        """
        获取带整数参数的临时二维码
        整数类型, 最小值1, 最大值为32位非0整型(十位数左右)
        最大支持　4294967295
        :return:
        """
        expires_in = self.get_argument("expires_in", 604800)
        scene_id = self.get_argument("scene_id", None)
        action = self.get_argument("action", "")

        if not scene_id:
            return self.finish(ret_msg(-1, error_message="缺少参数 scene_id"))

        qr_scene_obj = gen_qrcode_scene(scene_id=scene_id, limit=False,
                                        expires_in=expires_in, reset=action)
        return self.finish(qr_scene_obj['show'])
